package cn.sczhyt.modules.szhy.service.impl;

import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.common.utils.*;
import cn.sczhyt.modules.szhy.entity.MeetingFileEntity;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.sczhyt.modules.szhy.dao.MeetingVideoDao;
import cn.sczhyt.modules.szhy.entity.MeetingVideoEntity;
import cn.sczhyt.modules.szhy.service.MeetingVideoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service("meetingVideoService")
public class MeetingVideoServiceImpl extends ServiceImpl<MeetingVideoDao, MeetingVideoEntity> implements MeetingVideoService {



    /**
     * 文件配置
     */
    @Value("${cn.sczhyt.szhy.video.upload-path}")
    private  String videoPath;
     /**
     * 文件配置
     */
    @Value("${cn.sczhyt.szhy.video.server-path}")
    private  String videoServerPath;

    @Autowired
    private MeetingVideoDao meetingVideoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MeetingVideoEntity> page = this.page(
                new Query<MeetingVideoEntity>().getPage(params),
                new QueryWrapper<MeetingVideoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R saveMeetingVideo(MultipartFile[] files, String meetingId) {
        //根据时间创建文件夹
        String dateFile = DateUtils.format(new Date(), "yyyyMMddHHmm");

        String realPath = videoPath + dateFile;

        System.out.println( "真实路径" + realPath);
        File path = new File(realPath);

        if (!path.exists()) {
            path.mkdirs();
        }

        //保存文件
        if (files.length!=0) {

            for (int i = 0; i < files.length; i++) {
                try {

                    String originalFilename = files[i].getOriginalFilename();
                    //文件存储位置
                    String filepath = realPath + "/" + originalFilename;

                    System.out.println(filepath);

                    files[i].transferTo(new File(filepath));
                    //修改权限
                    Runtime.getRuntime().exec("chmod 755 " + videoPath + dateFile);
                    Runtime.getRuntime().exec("chmod 755 " + filepath);

                    //上传成功后对路径及文件名进行处理
                    MeetingVideoEntity meetingVideoEntity = new MeetingVideoEntity();
                    meetingVideoEntity.setMeetingId(meetingId);
                    meetingVideoEntity.setVideoName(originalFilename);
                    meetingVideoEntity.setVideoPath(videoServerPath + dateFile + "/" +originalFilename);
                    meetingVideoEntity.setVideoSize((int) (files[i].getSize() / 1024));
                    meetingVideoEntity.setCreateTime(new Date());
                    meetingVideoDao.insert(meetingVideoEntity);
                    return R.ok().put("data",meetingVideoEntity);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return R.error(2005,"上传文件为空！");
    }

    @Override
    public IPage<MeetingVideoEntity> findAll(Integer page, Integer limit, String meetingId) {

        Page<MeetingVideoEntity> pages = new Page<>(page, limit);

        return meetingVideoDao.findAll(pages, meetingId);
    }

    @Override
    public void download(String videoId, HttpServletResponse response, HttpServletRequest request) {

        MeetingVideoEntity meetingVideoEntity = meetingVideoDao.selectById(videoId);


        //真实路径/opt/zhyt-szhy/video
        //实际路径 http://118.24.254.66:8003/video/
        String[] split = meetingVideoEntity.getVideoPath().split("/video/");
        String path = split[1];
        System.out.println(path);
        File file = new File(videoPath + path);

        try {
            DownloadFileUtils.downloadFile(meetingVideoEntity.getVideoName(), file, response, request);

        } catch (UnsupportedEncodingException e) {
            throw new RRException("文件下载出错",201);
        }

    }

}